<template>
  <div class="login-container">
    <!-- 返回首页按钮和主题切换 -->
    <div class="back-home">
      <el-button 
        text 
        @click="$router.push('/')"
        class="back-btn"
      >
        <el-icon><ArrowLeft /></el-icon>
        {{ $t('common.home') }}
      </el-button>
      <ThemeToggle />
    </div>

    

    <div class="login-content">
      <div class="login-left">
        <div class="brand-section">
          <h1 class="brand-title">{{ $t('auth.brand.title') }}</h1>
          <p class="brand-subtitle">{{ $t('auth.brand.loginSubtitle') }}</p>
          <div class="feature-highlights">
            <div class="highlight-item">
              <div class="highlight-icon">🎭</div>
              <span>{{ $t('auth.brand.features.rolePlay') }}</span>
            </div>
            <div class="highlight-item">
              <div class="highlight-icon">🎙️</div>
              <span>{{ $t('auth.brand.features.voice') }}</span>
            </div>
            <div class="highlight-item">
              <div class="highlight-icon">🤖</div>
              <span>{{ $t('auth.brand.features.ai') }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="login-right">
    <div class="login-box">
      <div class="login-header">
        <h2>{{ $t('auth.login.title') }}</h2>
            <p>{{ $t('auth.login.subtitle') }}</p>
      </div>
      
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        size="large"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            :placeholder="$t('auth.login.username')"
            prefix-icon="User"
                :disabled="loading"
            clearable
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            :placeholder="$t('auth.login.password')"
            prefix-icon="Lock"
                :disabled="loading"
            show-password
            clearable
            @keyup.enter="handleLogin"
          />
        </el-form-item>
            
            <el-form-item prop="captcha">
              <div class="captcha-row">
                <el-input
                  v-model="loginForm.captcha"
                  :placeholder="$t('auth.login.captcha')"
                  :disabled="loading"
                  clearable
                  @keyup.enter="handleLogin"
                  style="flex: 1"
                >
                  <template #prefix>
                    <el-icon><Key /></el-icon>
                  </template>
                </el-input>
                <Captcha 
                  ref="captchaRef"
                  @change="handleCaptchaChange"
                  :width="120"
                  :height="40"
                />
              </div>
            </el-form-item>
        
        <el-form-item>
          <div class="login-options">
            <el-checkbox v-model="rememberMe" :disabled="loading">{{ $t('auth.login.rememberMe') }}</el-checkbox>
            <router-link to="/forgot-password" class="forgot-link">
              {{ $t('auth.login.forgotPassword') }}
            </router-link>
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            class="login-btn"
            :loading="loading"
                :disabled="loading"
            @click="handleLogin"
          >
                <el-icon v-if="!loading"><User /></el-icon>
                {{ loading ? $t('auth.login.loggingIn') : $t('auth.login.loginButton') }}
          </el-button>
        </el-form-item>
        
        <el-form-item>
          <div class="register-link">
            {{ $t('auth.login.noAccount') }}
            <router-link to="/register">{{ $t('auth.login.registerNow') }}</router-link>
          </div>
        </el-form-item>
      </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ElForm, ElMessage } from 'element-plus'
import { User, Lock, Key, ArrowLeft, ArrowDown } from '@element-plus/icons-vue'
import { useUserStore } from '../../store/modules/user'
import type { UserLogin } from '../../types/user'
import { defineAsyncComponent } from 'vue'
import { setLocale, getCurrentLocale, type SupportedLocale } from '../../i18n'
import ThemeToggle from '../../components/common/ThemeToggle.vue'
import { getRouteHistory } from '../../router'

const Captcha = defineAsyncComponent(() => import('../../components/Captcha.vue'))



const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const { t } = useI18n()

const loginFormRef = ref<InstanceType<typeof ElForm>>()
const captchaRef = ref()
const loading = ref(false)
const rememberMe = ref(false)
const currentCaptcha = ref('')
const currentLanguage = ref<SupportedLocale>(getCurrentLocale())

const loginForm = reactive<UserLogin & { captcha: string }>({
  username: '',
  password: '',
  captcha: ''
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: t('auth.validation.usernameRequired'), trigger: 'blur' },
    { min: 3, message: t('auth.validation.usernameMinLength'), trigger: 'blur' }
  ],
  password: [
    { required: true, message: t('auth.validation.passwordRequired'), trigger: 'blur' },
    { min: 6, message: t('auth.validation.passwordMinLength'), trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: t('auth.validation.captchaRequired'), trigger: 'blur' },
    { len: 4, message: t('auth.validation.captchaLength'), trigger: 'blur' }
  ]
}

const handleCaptchaChange = (code: string) => {
  currentCaptcha.value = code
}

const saveLoginInfo = () => {
  if (rememberMe.value) {
    localStorage.setItem('rememberedUsername', loginForm.username)
    localStorage.setItem('rememberedPassword', loginForm.password)
    localStorage.setItem('rememberMe', 'true')
  } else {
    localStorage.removeItem('rememberedUsername')
    localStorage.removeItem('rememberedPassword')
    localStorage.removeItem('rememberMe')
  }
}

const loadSavedLoginInfo = () => {
  const savedRememberMe = localStorage.getItem('rememberMe')
  if (savedRememberMe === 'true') {
    rememberMe.value = true
    loginForm.username = localStorage.getItem('rememberedUsername') || ''
    loginForm.password = localStorage.getItem('rememberedPassword') || ''
  }
}

const clearForm = () => {
  // 如果启用了记住我功能，只清空验证码，保留用户名和密码
  if (rememberMe.value) {
    loginForm.captcha = ''
  } else {
    loginForm.username = ''
    loginForm.password = ''
    loginForm.captcha = ''
  }
}

const refreshCaptchaAndClear = () => {
  if (captchaRef.value) {
    captchaRef.value.refresh()
  }
  loginForm.captcha = ''
}

const handleLanguageChange = (locale: SupportedLocale) => {
  currentLanguage.value = locale
  setLocale(locale)
}


// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    const valid = await loginFormRef.value.validate()
    if (!valid) return
    
    // 验证验证码
    if (!captchaRef.value?.validate(loginForm.captcha)) {
      ElMessage.error(t('auth.login.captchaError'))
      refreshCaptchaAndClear()
      return
    }
    
    loading.value = true
    const loginData = {
      username: loginForm.username,
      password: loginForm.password
    }
    await userStore.login(loginData)
    
    // 登录成功，保存登录信息
    saveLoginInfo()
    
    ElMessage.success({
      message: t('auth.login.loginSuccess'),
      duration: 3000,
      showClose: true
    })
    
    // 智能重定向逻辑
    const redirect = getSmartRedirect()
    router.push(redirect)
    
  } catch (error: any) {
    console.error('Login failed:', error)
    
    clearForm()
    refreshCaptchaAndClear()
    
    ElMessage.error({
      message: t('auth.login.loginFailed'),
      duration: 4000,
      showClose: true
    })
  } finally {
    loading.value = false
  }
}

// 智能重定向函数
const getSmartRedirect = (): string => {
  // 1. 优先使用URL中的redirect参数
  const urlRedirect = route.query.redirect as string
  if (urlRedirect && urlRedirect !== '/login' && urlRedirect !== '/register') {
    return urlRedirect
  }
  
  // 2. 检查localStorage中保存的lastRoute
  const savedRoute = localStorage.getItem('lastValidRoute')
  if (savedRoute && savedRoute !== '/login' && savedRoute !== '/register' && savedRoute !== '/forgot-password') {
    return savedRoute
  }
  
  // 3. 默认返回主页面
  return '/main'
}

// 组件挂载时加载保存的登录信息
onMounted(() => {
  loadSavedLoginInfo()
})
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.back-home {
  position: absolute;
  top: 20px;
  left: 20px;
  right: 20px;
  z-index: 10;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.language-switcher {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 10;
}

.back-btn {
  color: white;
  font-size: 16px;
  padding: 8px 16px;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
}

.lang-btn {
  color: white;
  font-size: 16px;
  padding: 8px 16px;
}

.lang-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
}

.login-content {
  max-width: 1000px;
  width: 100%;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 60px;
  align-items: center;
}

.login-left {
  color: white;
  padding: 40px;
}

.brand-section {
  text-align: left;
}

.brand-title {
  font-size: 48px;
  font-weight: 700;
  margin-bottom: 16px;
  background: linear-gradient(45deg, #fff, #e2e8f0);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.brand-subtitle {
  font-size: 20px;
  opacity: 0.9;
  margin-bottom: 40px;
  line-height: 1.6;
}

.feature-highlights {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.highlight-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.highlight-icon {
  font-size: 24px;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 8px;
}

.highlight-item span {
  font-size: 16px;
  font-weight: 500;
}

.login-right {
  display: flex;
  justify-content: center;
}

.login-box {
  background: white;
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
}

.login-header {
  text-align: center;
  margin-bottom: 32px;
}

.login-header h2 {
  font-size: 28px;
  font-weight: 700;
  color: #1a202c;
  margin-bottom: 8px;
}

.login-header p {
  color: #64748b;
  font-size: 16px;
}

.login-form {
  width: 100%;
}

.login-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

.login-form :deep(.el-input__wrapper) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e2e8f0;
  padding: 12px 16px;
  height: 48px;
}

.login-form :deep(.el-input__wrapper:hover) {
  border-color: #667eea;
}

.login-form :deep(.el-input__wrapper.is-focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.captcha-row {
  display: flex;
  gap: 12px;
  align-items: center;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.forgot-link {
  color: #667eea;
  text-decoration: none;
  font-size: 14px;
  transition: color 0.3s ease;
}

.forgot-link:hover {
  color: #5a67d8;
  text-decoration: underline;
}

.login-btn {
  width: 100%;
  height: 48px;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  transition: all 0.3s ease;
}

.login-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.register-link {
  text-align: center;
  color: #64748b;
  font-size: 14px;
}

.register-link a {
  color: #667eea;
  text-decoration: none;
  font-weight: 500;
  margin-left: 4px;
}

.register-link a:hover {
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-content {
    grid-template-columns: 1fr;
    gap: 40px;
    max-width: 400px;
  }
  
  .login-left {
    text-align: center;
    padding: 20px;
  }
  
  .brand-title {
    font-size: 36px;
  }
  
  .feature-highlights {
    display: none;
  }
  
  .login-box {
    padding: 30px 20px;
  }
}

@media (max-width: 480px) {
  .login-container {
    padding: 10px;
  }
  
  .login-box {
    padding: 24px 16px;
  }
  
  .login-header h2 {
    font-size: 24px;
  }
}

/* 深色模式样式 */
:global(.dark) .login-container {
  background: linear-gradient(135deg, #1e1b4b 0%, #312e81 100%) !important;
}

:global(.dark .login-box) {
  background: var(--surface) !important;
  border-color: var(--border) !important;
}

:global(.dark .login-header h2) {
  color: var(--text-primary) !important;
}

:global(.dark .login-header p) {
  color: var(--text-secondary) !important;
}

:global(.dark .brand-title) {
  color: var(--text-primary) !important;
}

:global(.dark .brand-subtitle) {
  color: var(--text-secondary) !important;
}

:global(.dark .highlight-item span) {
  color: var(--text-secondary) !important;
}

:global(.dark .back-btn) {
  color: var(--text-primary) !important;
}

:global(.dark .back-btn:hover) {
  background: rgba(255, 255, 255, 0.1) !important;
}

:global(.dark .login-footer-links .el-link) {
  color: var(--text-secondary) !important;
}

:global(.dark .login-footer-links .el-link:hover) {
  color: var(--primary-color) !important;
}
</style> 